package net.oschina.app.ui.fragments;

import java.util.ArrayList;
import java.util.List;

import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.adapter.ListViewQuestionAdapter;
import net.oschina.app.bean.Notice;
import net.oschina.app.bean.Post;
import net.oschina.app.bean.PostList;
import net.oschina.app.common.StringUtils;
import net.oschina.app.common.UIHelper;
import net.oschina.app.widget.NewDataToast;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class BaseQuestionListFragment extends MainPullToRefreshListFragment {
	private ListViewQuestionAdapter lvQuestionAdapter;
	private List<Post> lvQuestionData = new ArrayList<Post>();
	private Handler lvQuestionHandler;
	private int lvQuestionSumData;
	private int curQuestionCatalog;

	public BaseQuestionListFragment(int curQuestionCatalog,
			OnBaseListFragmentResumeListener baseListFragmentResumeListener) {
		super(baseListFragmentResumeListener);
		this.curQuestionCatalog = curQuestionCatalog;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initQuestionListView();
	}
	@Override
	public void onDestroyView() {
		lvQuestionData.clear();
		super.onDestroyView();
	}
	/**
	 * 初始化帖子列表
	 */
	private void initQuestionListView() {
		lvQuestionAdapter = new ListViewQuestionAdapter(getActivity(),
				lvQuestionData, R.layout.question_listitem);
		listView.addFooterView(list_footer);// 添加底部视图 必须在setAdapter前
		listView.setAdapter(lvQuestionAdapter);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 点击头部、底部栏无效
				if (view == list_footer)
					return;

				Post post = null;
				// 判断是否是TextView
				if (view instanceof TextView) {
					post = (Post) view.getTag();
				} else {
					TextView tv = (TextView) view
							.findViewById(R.id.question_listitem_title);
					post = (Post) tv.getTag();
				}
				if (post == null)
					return;

				// 跳转到问答详情
				UIHelper.showQuestionDetail(view.getContext(), post.getId());
			}
		});
		listView.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {

				// 数据为空--不用继续下面代码了
				if (lvQuestionData.isEmpty())
					return;

				// 判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(list_footer) == view
							.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = StringUtils.toInt(listView.getTag());
				if (scrollEnd && lvDataState == UIHelper.LISTVIEW_DATA_MORE) {
					listView.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					list_foot_more.setText(R.string.load_ing);
					list_foot_progress.setVisibility(View.VISIBLE);
					// 当前pageIndex
					int pageIndex = lvQuestionSumData / AppContext.PAGE_SIZE;
					loadLvQuestionData(curQuestionCatalog, pageIndex,
							lvQuestionHandler, UIHelper.LISTVIEW_ACTION_SCROLL);

				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

			}
		});
		lvQuestionHandler = this.getLvHandler(listView, lvQuestionAdapter,
				list_foot_more, list_foot_progress, AppContext.PAGE_SIZE);
	}

	/**
	 * 线程加载帖子数据
	 * 
	 * @param catalog
	 *            分类
	 * @param pageIndex
	 *            当前页数
	 * @param handler
	 *            处理器
	 * @param action
	 *            动作标识
	 */
	private void loadLvQuestionData(final int catalog, final int pageIndex,
			final Handler handler, final int action) {
		mPullToRefreshAttacher.setRefreshing(true);
		new Thread() {
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH
						|| action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				try {
					PostList list = appContext.getPostList(catalog, pageIndex,
							isRefresh);
					msg.what = list.getPageSize();
					msg.obj = list;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;
				msg.arg2 = UIHelper.LISTVIEW_DATATYPE_POST;
				if (curQuestionCatalog == catalog)
					handler.sendMessage(msg);
			}
		}.start();
	}

	/**
	 * listview数据处理
	 * 
	 * @param what
	 *            数量
	 * @param obj
	 *            数据
	 * @param objtype
	 *            数据类型
	 * @param actiontype
	 *            操作类型
	 * @return notice 通知信息
	 */
	private Notice handleLvData(int what, Object obj, int objtype,
			int actiontype) {
		Notice notice = null;
		switch (actiontype) {
		case UIHelper.LISTVIEW_ACTION_INIT:
		case UIHelper.LISTVIEW_ACTION_REFRESH:
		case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
			int newdata = 0;// 新加载数据-只有刷新动作才会使用到
			switch (objtype) {
			case UIHelper.LISTVIEW_DATATYPE_POST:
				PostList plist = (PostList) obj;
				notice = plist.getNotice();
				lvQuestionSumData = what;
				if (actiontype == UIHelper.LISTVIEW_ACTION_REFRESH) {
					if (lvQuestionData.size() > 0) {
						for (Post post1 : plist.getPostlist()) {
							boolean b = false;
							for (Post post2 : lvQuestionData) {
								if (post1.getId() == post2.getId()) {
									b = true;
									break;
								}
							}
							if (!b)
								newdata++;
						}
					} else {
						newdata = what;
					}
				}
				lvQuestionData.clear();// 先清除原有数据
				lvQuestionData.addAll(plist.getPostlist());
				break;
			}
			if (actiontype == UIHelper.LISTVIEW_ACTION_REFRESH && isVisible()) {
				// 提示新加载数据
				if (newdata > 0) {
					NewDataToast
							.makeText(
									getActivity(),
									getString(R.string.new_data_toast_message,
											newdata), appContext.isAppSound())
							.show();
				} else {
					NewDataToast.makeText(getActivity(),
							getString(R.string.new_data_toast_none), false)
							.show();
				}
			}
			break;
		case UIHelper.LISTVIEW_DATATYPE_POST:
			PostList plist = (PostList) obj;
			notice = plist.getNotice();
			lvQuestionSumData += what;
			if (lvQuestionData.size() > 0) {
				for (Post post1 : plist.getPostlist()) {
					boolean b = false;
					for (Post post2 : lvQuestionData) {
						if (post1.getId() == post2.getId()) {
							b = true;
							break;
						}
					}
					if (!b)
						lvQuestionData.add(post1);
				}
			} else {
				lvQuestionData.addAll(plist.getPostlist());
			}
			break;
		}
		return notice;
	}

	/**
	 * 获取listview的初始化Handler
	 * 
	 * @param lv
	 * @param adapter
	 * @return
	 */
	protected Handler getLvHandler(final ListView lv,
			final BaseAdapter adapter, final TextView more,
			final ProgressBar progress, final int pageSize) {
		return new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what >= 0) {
					// listview数据处理
					Notice notice = handleLvData(msg.what, msg.obj, msg.arg2,
							msg.arg1);

					if (msg.what < pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_FULL);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_full);
					} else if (msg.what == pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_more);

					}
					// 发送通知广播
					if (notice != null) {
						UIHelper.sendBroadCast(lv.getContext(), notice);
					}
				} else if (msg.what == -1) {
					// 有异常--显示加载出错 & 弹出错误消息
					lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
					more.setText(R.string.load_error);
					((AppException) msg.obj).makeToast(getActivity());
				}
				if (adapter.getCount() == 0) {
					lv.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					more.setText(R.string.load_empty);
				}
				progress.setVisibility(ProgressBar.GONE);
				mPullToRefreshAttacher.setRefreshComplete();
				if (msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH) {
					// getFragmentActivity().setActionBarSubtitle(getString(R.string.pull_to_refresh_update)
					// + new Date().toLocaleString());
					lv.setSelection(0);
				} else if (msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG) {
					lv.setSelection(0);
				}
			}
		};
	}

	@Override
	public void onRefreshStarted(View view) {
		loadLvQuestionData(curQuestionCatalog, 0, lvQuestionHandler,
				UIHelper.LISTVIEW_ACTION_REFRESH);

	}

	@Override
	public void showList() {
		if(!isHasInit()) {
			loadLvQuestionData(curQuestionCatalog, 0, lvQuestionHandler,
					UIHelper.LISTVIEW_ACTION_INIT);
			setHasInit(true);
		}
	}
}
